<?php
/**
 * 处理会员业务
 * @author ym.liu
 *
 */
class verification_members {
	
	//检查会员是否合法
	protected function checkMember($member_id, $sid = ''){
		session_id($sid);
		session_start();
		if($member_id != $_SESSION['member_id']){
			return array(
					'status'=>false,
					'code'=>'00008'
			);
		}
		return array('status'=>true);
	}
	
	// 会员登录
	public function login($username, $password, $type, $num) {
		$data = array(
			'username'=>$username,
			'password'=>$password,
			'type'=>$type,
		);
		//检查会员信息
		$cRes = kernel::single('verification_mdl_members')->validate($data, false);

		if(!$cRes['status']){
			return $cRes;
		}

		$info = kernel::single ( 'verification_mdl_members' )->getMemberInfo ( $username, $password, $type, $num );

		session_start();
		// 存储session
		$_SESSION ['member_id'] = $info['data'] ['member_id']; // 账户id号
		$_SESSION ['username'] = $info['data']['username'];	//用户名
		$_SESSION ['store_id'] = $info['data'] ['store_id'];	//门店ID号
		$_SESSION ['seller_id'] = $info['data']['seller_id'];	//商户ID
		$info['data']['sid'] = session_id();
		
		//更新用户最后一次登录时间
		$updata = array(
			'last_time'=>time()
		);
		$filter = array(
			'member_id'=>$_SESSION['member_id']
		);
		app::get('verification')->model('members')->update($updata, $filter);
		
		return $info;
	}
	
	// 会员登出
	public function logOut($member_id,$password,$sid) {

		$this->checkMember($member_id, $sid);
		
		if ($member_id != $_SESSION ['member_id']) {
			return array (
					'status'=>false,
					'code' => '00003'
			);
		}
		
		$member = app::get ( 'verification' )->model ( 'members' )->getList ( 'username, password', array (
				'member_id' => $member_id 
		) );
		
		if ($password != md5 ( $member [0] ['password'] )) {
			return array (
					'status'=>false,
					'code' => '00003'
			);
		}
		
		// 删除session
		$_SESSION ['member_id'] = null; // 账户id号
		$_SESSION ['store_id'] = null;	//门店ID号
		$_SESSION ['seller_id'] = null;	//商户ID
		
		return array (
				'status'=>true,
				'code' => '00000'
		);
	}
	
	//修改密码
	public function resetPssword($member_id, $password, $newPassword, $sid){
		
		$this->checkMember($member_id, $sid);

		//验证原密码是否正确
		$member = app::get('verification')->model('members')->getList('password', array('member_id'=>$member_id));

		if($member[0]['password'] != md5($password)){
			return array('status'=>false, 'code'=>'10005');
		}
		$data = array(
			'password'=>md5($newPassword)
		);
		$filter = array(
			'member_id'=>$member_id,
		);
		$res = app::get('verification')->model('members')->update($data, $filter);
		if($res){
			return array('status'=>true, 'code'=>'00000');
		} else {
			return array('status'=>false, 'code'=>'00001');
		}
	}

/**
 * 析构方法
 */
	private function __destruct(){
		//销毁session
		session_destroy();
	}
}